package com.tp.controller.system;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.tp.base.BaseController;
import com.tp.model.sys.SysRole;
import com.tp.service.MenuService;
import com.tp.service.RoleService;

/**
 * 角色管理
 * 
 * @author TP
 *
 */
@ControllerBind(controllerKey = "/system/role")
public class RoleController extends BaseController {

	private static final String path = "/pages/system/role/role_";

	@Inject
	RoleService service;

	@Inject
	MenuService menuService;

	public void index() {
		render(path + "list.html");
	}

	public void list() {
		SysRole model = getModelByAttr(SysRole.class);
		// 排序
		String orderBy = getBaseForm().getOrderBy();
		Page<SysRole> page = service.getPageByWhere(model, orderBy, getPaginator());
		renderCount(page.getTotalRow(), page.getList());
	}

	public void form() {
		int id = getParaToInt("id", 0);
		if (id == 0) {
			SysRole model = new SysRole();
			model.setStatus(1);
			setAttr("model", model);
		} else {
			SysRole model = new SysRole().dao().findById(id);
			setAttr("model", model);
		}
		render(path + "form.html");
	}

	public void save() {
		SysRole model = getModel(SysRole.class);
		boolean flag = false;
		if (model.getInt("id") != null && model.getInt("id") > 0) { // 更新
			model.put("update_id", getUID());
			model.put("update_time", getNow());
			flag = model.update();
		} else { // 新增
			model.remove("id");
			model.put("create_id", getUID());
			model.put("create_time", getNow());
			flag = model.save();
		}
		if (flag) {
			renderOk("保存成功");
		} else {
			renderFail("保存失败");
		}
	}

	@Before(Tx.class)
	public void delete() {
		Integer uid = getUID();
		String[] ids = getPara("ids").split(",");
		boolean flag = service.deleteObject(ids, uid);
		if (flag) {
			renderOk("删除成功");
		} else {
			renderFail("删除失败");
		}
	}

	public void setAuth() {
		int rId = getParaToInt("rId", 0);
		setAttr("rootList", menuService.getTreeList());
		setAttr("menuIds", service.getRoleMenu(rId));
		render(path + "auth.html");
	}

	@Before(Tx.class)
	public void saveAuht() {
		int roleid = getParaToInt("rId");
		String mIds = getPara("mIds");
		boolean flag = service.saveRoleAuth(roleid, mIds, getUID());
		if (flag) {
			renderOk("设置成功");
		} else {
			renderFail("设置失败");
		}
	}
}
